package com.customization.commons;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.util.UUID;


/**
 * @author liutaihong
 * @version 1.0.0
 * @ClassName WSDLUtil.java
 * @Description  这是一个post的工具类 支持基于basic认证的接口调用
 * @createTime 2020-06-02 18:01:03
 */
public class WSDLUtil extends BaseBean {
    private HttpClientBuilder httpClientBuilder;
    private CloseableHttpClient closeableHttpClient;

    private  String username;
    private  String passowrd;
    private  String uri;

    public WSDLUtil() {

        BaseBean baseBean= new BaseBean();
        this.username=baseBean.getPropValue("angel_fna","ssf_basic_username");
        this.passowrd=baseBean.getPropValue("angel_fna","ssf_basic_passowrd");
        this.uri=baseBean.getPropValue("angel_fna","ssf_basic_uri");

    }


    public String HttpClientPostByBasic(String  url, String content){
        if(!url.startsWith("http")){
            url=this.uri+url;
        }
        return HttpClientByBasic(  url,  content,  this.username,  this.passowrd,"post").getString("result");
    }

    /**
     * POST方式调用 BASIC认证
     * @param url 接口地址
     * @param content 内容
     * @param request 流程对象
     * @return
     */
    public String HttpClientPostByBasic(String  url, String content, RequestInfo request){
                if(!url.startsWith("http")){
                    url=this.uri+url;
                }
                 Console.info("-------------------------------Start------------------------------------");
                 Console.info("流程标题:" + request.getRequestManager().getRequestname());//打印日志
                 Console.info("流程请求ID:" + request.getRequestManager().getRequestid());//打印日志



                JSONObject json= HttpClientByBasic( url,  content,  this.username,  this.passowrd,"post");



             String result= json.getString("result");
             Console.info("-------------------------------End--------------------------------------");
        return result;
    }

    /**
     * GET方式调用 BASIC认证
     * @param url 接口地址
     * @param content 内容
     * @return
     */
    public String HttpClientGetByBasic(String  url, String content){
        if(!url.startsWith("http")){
            url=this.uri+url;
        }
        return HttpClientByBasic(  url,  content,  this.username,  this.passowrd,"get").getString("result");
    }


    /**
     * POST方式调用 BASIC认证  传递BASIC用户名和密码
     * @param url 地址
     * @param content 内容
     * @param username basic用户名
     * @param password basic密码
     * @return
     */
    public JSONObject HttpClientPostByBasic(String  url, String content, String username, String password){
        return HttpClientByBasic(  url,  content,  username,  password,"post");
    }

    /**
     *
     * get方式调用 BASIC认证  传递BASIC用户名和密码
     * @param url 地址
     * @param content 内容
     * @param username basic用户名
     * @param password basic密码
     * @return
     */
    public JSONObject HttpClientGetByBasic(String  url, String content, String username, String password){
        return HttpClientByBasic(  url,  content,  username,  password,"get");
    }

    private JSONObject HttpClientByBasic(String  psotaddress, String content, String username, String password, String method) {
        JSONObject json=new JSONObject();
       //content="<!DOCTYPE root [<!ENTITY nbsp \" \"><!ENTITY copy \"©\"><!ENTITY reg \"®\"><!ENTITY trade \"™\"><!ENTITY mdash \"—\"><!ENTITY ldquo \"“\"><!ENTITY rdquo \"”\"><!ENTITY pound \"£\"><!ENTITY yen \"¥\"><!ENTITY euro \"€\">]>"+content;
        String uuid= UUID.randomUUID().toString();
        long time=0l;
        this.createCloseableHttpClientWithBasicAuth(username, password);
        String result = "";

        CloseableHttpResponse closeableHttpResponse = null;
        HttpEntity httpEntity = null;


        try {
            if("get".equals(method)) {
                HttpGet httpGet=null;
                httpGet = new HttpGet(psotaddress);
                closeableHttpResponse = this.closeableHttpClient.execute(httpGet);
            }else{
                HttpPost httpPost = null;

                httpPost = new HttpPost(psotaddress);
                RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000*60*30).setConnectTimeout(1000*60*30).build();//设置请求和传输超时时间
                httpPost.setConfig(requestConfig);
                httpPost.setHeader("Content-Type",
                        "text/xml;charset=UTF-8");
               // System.out.println("addr:"+psotaddress);
                 Console.info(uuid+"请求地址："+psotaddress);
                StringEntity  stringEntity = null;
                if(!content.equals("")) {
                    //存在&就转义  &amp
                    content = content.replace("&", "&amp;");
                    stringEntity = new StringEntity(content, "UTF-8");
                }

                httpPost.setEntity(stringEntity);

                 Console.info(uuid+"-start--------------");
                 Console.info(uuid+"请求报文："+content);
                //System.out.println("请求报文："+XmlUtil.formatXml(content));
                long startreadSap = System.currentTimeMillis();
                closeableHttpResponse = this.closeableHttpClient.execute(httpPost);
                time=System.currentTimeMillis() - startreadSap;
                 Console.info(uuid+"耗时"+time+"ms");

            }
            httpEntity = closeableHttpResponse.getEntity();
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity);
                // Console.info("--------------------------");
                 Console.info(uuid+"请求返回值："+result);
                //System.out.println("请求返回值："+XmlUtil.formatXml(result));
            }
        } catch (ClientProtocolException  e) {
            result=e.toString();
             Console.info("发送报文ClientProtocolException异常:"+ e.toString());
             e.printStackTrace();
        } catch (IOException  e) {
            result=e.toString();
             Console.info("发送报文IOException异常:"+ e.toString());
             e.printStackTrace();
        }
        json.put("result",result);
        json.put("time",time);

        return json;
    }

    /**
     * POST方式调用接口
     * @param psotaddress 接口地址
     * @param content 内容
     * @return
     */
    public JSONObject HttpClientPost(String  psotaddress, String content) {
        return HttpClient(psotaddress,  content, "post");
    }

    /**
     * Get方式调用接口
     * @param psotaddress 接口地址
     * @param content 内容
     * @return
     */

    public JSONObject HttpClientGet(String  psotaddress, String content) {
        return HttpClient(psotaddress,  content, "get");
    }


    private JSONObject HttpClient(String  psotaddress, String content, String method) {
        JSONObject json=new JSONObject();

       /* content="<!DOCTYPE root [" +

                "<!ENTITY nbsp \" \">" +
                "<!ENTITY copy \"©\">" +
                "<!ENTITY reg \"®\">" +
                "<!ENTITY trade \"™\">" +
                "<!ENTITY mdash \"—\">" +
                "<!ENTITY ldquo \"“\">" +
                "<!ENTITY rdquo \"”\">" +
                "<!ENTITY pound \"£\">" +
                "<!ENTITY yen \"¥\">" +
                "<!ENTITY euro \"€\">" +
                "]>"+content;

        */

        String uuid= UUID.randomUUID().toString();
        long time=0l;
        this.createCloseableHttpClient();
        String result = "";

        CloseableHttpResponse closeableHttpResponse = null;
        HttpEntity httpEntity = null;

        try {
            if("get".equals(method)) {
                HttpGet httpGet=null;
                httpGet = new HttpGet(psotaddress);
                closeableHttpResponse = this.closeableHttpClient.execute(httpGet);
            }else{
                HttpPost httpPost = null;

                httpPost = new HttpPost(psotaddress);
                RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000*60*30).setConnectTimeout(1000*60*30).build();//设置请求和传输超时时间
                httpPost.setConfig(requestConfig);
                httpPost.setHeader("Content-Type",
                        "application/soap+xml;charset=UTF-8");
                Console.info(uuid+"请求地址："+psotaddress);
                StringEntity  stringEntity = null;
                if(!content.equals("")) {
                    //存在&就转义  &amp
                    content = content.replace("&", "&amp;");
                    stringEntity = new StringEntity(content, "UTF-8");
                }

                httpPost.setEntity(stringEntity);

                Console.info(uuid+"-start--------------");
                Console.info(uuid+"请求报文："+content);
                //System.out.println("请求报文："+XmlUtil.formatXml(content));
                long startreadSap = System.currentTimeMillis();
                closeableHttpResponse = this.closeableHttpClient.execute(httpPost);
                time=System.currentTimeMillis() - startreadSap;
                Console.info(uuid+"耗时"+time+"ms");

            }
            httpEntity = closeableHttpResponse.getEntity();
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity);
                // Console.info("--------------------------");
                Console.info(uuid+"请求返回值："+result);
                //System.out.println("请求返回值："+XmlUtil.formatXml(result));
            }
        } catch (ClientProtocolException  e) {
            result=e.toString();
            Console.info("发送报文ClientProtocolException异常:"+ e.toString());
            e.printStackTrace();
        } catch (IOException  e) {
            result=e.toString();
            Console.info("发送报文IOException异常:"+ e.toString());
            e.printStackTrace();
        }
        json.put("result",result);
        json.put("time",time);

        return json;
    }


    private void closeHttpClient() {
        if (this.closeableHttpClient != null) {
            try {
                this.closeableHttpClient.close();
            } catch (IOException content) {
                this.writeLog(content);
                content.printStackTrace();
            }
        }

    }

    private void createCloseableHttpClient() {
        if (this.closeableHttpClient == null) {
            this.httpClientBuilder = HttpClientBuilder.create();
            this.closeableHttpClient = this.httpClientBuilder.build();
        }

    }

    private void createCloseableHttpClientWithBasicAuth(String  url, String content) {
        if (this.closeableHttpClient == null) {
            this.httpClientBuilder = HttpClientBuilder.create();
            BasicCredentialsProvider username = new BasicCredentialsProvider();
            AuthScope password = new AuthScope(AuthScope.ANY_HOST, -1, AuthScope.ANY_REALM);
            UsernamePasswordCredentials var5 = new UsernamePasswordCredentials( url, content);
            username.setCredentials(password, var5);
            this.httpClientBuilder.setDefaultCredentialsProvider(username);
            this.closeableHttpClient = this.httpClientBuilder.build();
        }

    }

}
